/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dataAccess;

import dataAccess.exceptions.NonexistentEntityException;
import dataAccess.exceptions.PreexistingEntityException;
import entities.Device;
import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import entities.Lab;
import entities.Report;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;

/**
 *
 * @author QUY-THI
 */
public class DeviceJpaController implements Serializable {

    public DeviceJpaController(EntityManagerFactory emf) {
        this.emf = emf;
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Device device) throws PreexistingEntityException, Exception {
        if (device.getReportList() == null) {
            device.setReportList(new ArrayList<Report>());
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Lab labID = device.getLabID();
            if (labID != null) {
                labID = em.getReference(labID.getClass(), labID.getLabID());
                device.setLabID(labID);
            }
            List<Report> attachedReportList = new ArrayList<Report>();
            for (Report reportListReportToAttach : device.getReportList()) {
                reportListReportToAttach = em.getReference(reportListReportToAttach.getClass(), reportListReportToAttach.getReportID());
                attachedReportList.add(reportListReportToAttach);
            }
            device.setReportList(attachedReportList);
            em.persist(device);
            if (labID != null) {
                labID.getDeviceList().add(device);
                labID = em.merge(labID);
            }
            for (Report reportListReport : device.getReportList()) {
                Device oldDeviceIDOfReportListReport = reportListReport.getDeviceID();
                reportListReport.setDeviceID(device);
                reportListReport = em.merge(reportListReport);
                if (oldDeviceIDOfReportListReport != null) {
                    oldDeviceIDOfReportListReport.getReportList().remove(reportListReport);
                    oldDeviceIDOfReportListReport = em.merge(oldDeviceIDOfReportListReport);
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            if (findDevice(device.getDeviceID()) != null) {
                throw new PreexistingEntityException("Device " + device + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Device device) throws NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Device persistentDevice = em.find(Device.class, device.getDeviceID());
            Lab labIDOld = persistentDevice.getLabID();
            Lab labIDNew = device.getLabID();
            List<Report> reportListOld = persistentDevice.getReportList();
            List<Report> reportListNew = device.getReportList();
            if (labIDNew != null) {
                labIDNew = em.getReference(labIDNew.getClass(), labIDNew.getLabID());
                device.setLabID(labIDNew);
            }
            List<Report> attachedReportListNew = new ArrayList<Report>();
            for (Report reportListNewReportToAttach : reportListNew) {
                reportListNewReportToAttach = em.getReference(reportListNewReportToAttach.getClass(), reportListNewReportToAttach.getReportID());
                attachedReportListNew.add(reportListNewReportToAttach);
            }
            reportListNew = attachedReportListNew;
            device.setReportList(reportListNew);
            device = em.merge(device);
            if (labIDOld != null && !labIDOld.equals(labIDNew)) {
                labIDOld.getDeviceList().remove(device);
                labIDOld = em.merge(labIDOld);
            }
            if (labIDNew != null && !labIDNew.equals(labIDOld)) {
                labIDNew.getDeviceList().add(device);
                labIDNew = em.merge(labIDNew);
            }
            for (Report reportListOldReport : reportListOld) {
                if (!reportListNew.contains(reportListOldReport)) {
                    reportListOldReport.setDeviceID(null);
                    reportListOldReport = em.merge(reportListOldReport);
                }
            }
            for (Report reportListNewReport : reportListNew) {
                if (!reportListOld.contains(reportListNewReport)) {
                    Device oldDeviceIDOfReportListNewReport = reportListNewReport.getDeviceID();
                    reportListNewReport.setDeviceID(device);
                    reportListNewReport = em.merge(reportListNewReport);
                    if (oldDeviceIDOfReportListNewReport != null && !oldDeviceIDOfReportListNewReport.equals(device)) {
                        oldDeviceIDOfReportListNewReport.getReportList().remove(reportListNewReport);
                        oldDeviceIDOfReportListNewReport = em.merge(oldDeviceIDOfReportListNewReport);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = device.getDeviceID();
                if (findDevice(id) == null) {
                    throw new NonexistentEntityException("The device with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Device device;
            try {
                device = em.getReference(Device.class, id);
                device.getDeviceID();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The device with id " + id + " no longer exists.", enfe);
            }
            Lab labID = device.getLabID();
            if (labID != null) {
                labID.getDeviceList().remove(device);
                labID = em.merge(labID);
            }
            List<Report> reportList = device.getReportList();
            for (Report reportListReport : reportList) {
                reportListReport.setDeviceID(null);
                reportListReport = em.merge(reportListReport);
            }
            em.remove(device);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Device> findDeviceEntities() {
        return findDeviceEntities(true, -1, -1);
    }

    public List<Device> findDeviceEntities(int maxResults, int firstResult) {
        return findDeviceEntities(false, maxResults, firstResult);
    }

    private List<Device> findDeviceEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Device.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Device findDevice(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Device.class, id);
        } finally {
            em.close();
        }
    }

    public int getDeviceCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Device> rt = cq.from(Device.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
